//
//  EditViewController.swift
//  SinaWeibo
//
//  Created by apple on 15/11/19.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class EditViewController: UIViewController {
    
    //监听按钮的点击事件
    @objc  func selectPicture() {
        
        //改变视图的约束
        
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            
            
            make.height.equalTo(224 + 80 + 40)
        }

        
        
    }
    @objc func cancel() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func present() {
        
        let urlString = "2/statuses/update.json"
        
        guard let token = UserAccountViewModel().token else {
            
            SVProgressHUD.showErrorWithStatus("您暂时未登陆")
            return
        }
        let paramters = ["access_token":token,"status":textView.text]
        
        NetWorkingTools.shareTools.requestJSONDict(.POST, urlString: urlString, parameters: paramters) { (result, error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("请检查网络")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("您已经成功发布一条微博")
            self.dismissViewControllerAnimated(true, completion: nil)
            
            
        }
       
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUPUI()
    }
    
    //MARK 初始化方法
    //MARK 设置UI
    private func setUPUI() {
        
        setNavBar()
        
        setinputView()
        
        setToolBar()
        
        //增加图片选择控制器
        selectPicView()
        //注册通知
        registerNotification()
    }
    
    private func selectPicView() {
        
        //添加子控制器
        addChildViewController(selectorVC)
        
        //添加子视图
        view.addSubview(selectorVC.view)
        
        //调整视图层次结构
        view.bringSubviewToFront(toolBar)
        
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.bottom.right.equalTo(view)
            
            make.height.equalTo(0)
        }
    
    }
    //注册通知 这个通知是由系统发出的
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    @objc private func keyboardWillChangeFrame(note:NSNotification) {
        
        print(note)
        
        //获取rect 
        let rect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
        
        let offset = -screenHeight + (rect?.origin.y)!
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(offset)
        }
        //强制刷新
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK 懒加载控件
    private lazy var titleLabel : UILabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
    
    
    private lazy var nameLabel :UILabel = UILabel(title: UserAccountViewModel().name ?? "", size: 14, color: UIColor.darkGrayColor())
    
    
    //文本输入框
    private lazy var textView :UITextView = {
        
        let tv  = UITextView()
        
        tv.delegate = self
        
        tv.textColor = UIColor.darkGrayColor()
        
        tv.font = UIFont.systemFontOfSize(18)
        
        //设置键盘消失样式
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.alwaysBounceVertical = true
        
        return tv
        
        }()
    
    //占位文本
    private lazy var placeholderText :UILabel = UILabel(title: "分享新鲜事......", size: 18, color: UIColor.darkGrayColor())
    
    //toolBar
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    //增加图片选择控制器

    private lazy var selectorVC : PictureSelectorViewController = PictureSelectorViewController()
}

extension EditViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        //隐藏站位文本
        placeholderText.hidden = textView.hasText()
        
        //发布按钮禁用
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
/**
*  分类 只能增加方法  不能增加属性
*/
extension EditViewController  {
    
    
    //定义输入文本框
    private func setinputView() {
        
        view.addSubview(textView)
        textView.backgroundColor = UIColor.randomColor()
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.left.right.equalTo(self.view)
            
            make.height.equalTo(self.view.bounds.height / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeholderText)
        
        //设置约束
        placeholderText.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(8)
            
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    //自定义toolBar
    private func setToolBar() {
        
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        
        var items = [UIBarButtonItem]()
        
        //添加 UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
            
          let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])

            items.append(item)
            //实例化弹簧
           let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)

            items.append(space)
        }
        
        //删除最后一个弹簧
        items.removeLast()

        toolBar.items = items
    }
    //自定义导航条
    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancel")
        
        self.navigationItem.rightBarButtonItem  = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "present")
        
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 40))
        
        titleView.backgroundColor = UIColor.lightGrayColor()
        
        navigationItem.titleView = titleView
        
        titleView.addSubview(titleLabel)
        
        titleView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(titleView.snp_top)
            
            make.centerX.equalTo(titleView.snp_centerX)
            
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(titleView.snp_bottom)
            
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    
    
}